package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcUtils {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        add("admin","123");
    }
    public static  void add(String username,String password) throws ClassNotFoundException, SQLException {
        //加载并注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //获取数据空链接对象
        String url="jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf8";
        String user="root";
        String pwd="123456";
        Connection connection = null;
        connection = DriverManager.getConnection(url,user,pwd);
        //获取preparedStatement对象
        String sql="insert into user(username,password) values(?,?)";
        PreparedStatement pstmt=connection.prepareStatement(sql);
        pstmt.setString(1,username);
        pstmt.setString(2,password);
        int count=pstmt.executeUpdate();
        if(count>0){
            System.out.println("数据添加成功");
        }else {
            System.out.println("数据添加失败");
        }
        //资源释放
        if(pstmt!=null){

            pstmt.close();
            pstmt=null;
        }
        if(connection!=null){
            connection.close();
            connection=null;
        }

    }
}
